from datetime import datetime
import requests

import pandas as pd

from air_web.data_platform import sql_engine


ORG_MAP = {'51401': '510100',
           '51402': '511700',
           '51403': '511300',
           '51404': '511000',
           '51405': '511500',
           '51406': '510300',
           '51407': '510500',
           '51408': '510400',
           '51409': '513400',
           '51410': '510700',
           '51411': '511100',
           '51412': '510600',
           '51413': '510800',
           '51414': '511900',
           '51415': '511600',
           '51416': '511400',
           '51417': '512000',
           '51421': '510900',
           '51486': '511800',
           '51490': '513200',
           '51517': '513300'}

URL = "http://25.214.202.174:20085/fhgl-sc-dispatch/dataApi/load/real"
MEAS_TYPE = "11032001"


def post_data(data):
    # test = {MEAS_TYPE:[{"time": "00:00:00", "value": "1"},{"time": "00:15:00", "value": "2"}]}
    # return test
    for i in range(3):
        resp = requests.post(url=URL, json=data)
        if resp.status_code == 200:
            print("获取总负荷成功")
            return resp.json()['data']
        else:
            print("获取总负荷失败", resp.json())
            return None


def max_p_total_access():
    start_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).strftime(
        '%Y-%m-%d %H:%M:%S')
    end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    today = start_time[0:10]

    res_list = []
    all_df = pd.DataFrame()
    for org_no, district_code in ORG_MAP.items():
        print(f"发起请求: {URL}, {district_code}")
        post_dict = {"districtCode": district_code,
                     "measType": MEAS_TYPE,
                     "startTime": start_time,
                     "endTime": end_time,
                     "interval": "1",
                     "timeSpace": "15"}
        data = post_data(post_dict)
        if data is None:
            continue
        data_list = data[MEAS_TYPE]
        if len(data_list) == 0:
            print("总负荷数据为空")
            continue

        df = pd.DataFrame(data_list)
        df['value'] = df['value'].astype("float64") * 1000  # 原始单位是MW,1MW=1000KW

        all_df = pd.concat([all_df, df])
        max_p_total = df['value'].max()

        res_list.append({"on5": org_no, "data_time": today, "write_max_p_total": max_p_total})
    if not all_df.empty:
        pro_max_p_total = all_df.groupby("time")["value"].sum().max()
        res_list.append({"on5": '51101', "data_time": today, "write_max_p_total": pro_max_p_total})

    res_df = pd.DataFrame(res_list)
    if not res_df.empty:
        sql_engine.update_df_by_id(res_df, "city_write")


if __name__ == '__main__':
    max_p_total_access()
